
<template>
  <div class="content" :class="{ 'is-mobile': isMobile }">
    <heads :current="1"></heads>
    <div class="main">
      <div class="payment-container">
        <!-- Order Summary -->
        <div class="order-summary">
          <h2>{{ $t('payment.orderDetails') }}</h2>
          <div class="summary-content">
            <div class="summary-item">
              <span class="label">{{ $t('payment.orderNumber') }}</span>
              <span class="value">{{ order.order_no }}</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('payment.trip') }}</span>
              <span class="value">{{ order.ship.name }}</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('payment.tripDate') }}</span>
              <span class="value">{{ order.cycle.start_time }}</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('payment.tripDuration') }}</span>
              <span class="value">{{ order.ship.duration || order.cycle.duration}}h</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('payment.createDate') }}</span>
              <span class="value">{{ order.create_time }}</span>
            </div>
            <div class="summary-item">
              <span class="label">{{ $t('payment.passengerCount') }}</span>
              <span class="value">{{ order.count }}</span>
            </div>
            <div class="summary-item total">
              <span class="label">{{ $t('payment.paymentAmount') }}</span>
              <span class="value">${{ order.amount }}</span>
            </div>
          </div>
        </div>

        <!-- Payment Methods -->
        <div class="payment-section">
          <h3>{{ $t('payment.selectPaymentMethod') }}</h3>

          <!-- Alipay Method Selection -->
          <div class="alipay-methods">
            <div
              v-for="method in paymentMethods"
              :key="method.id"
              class="alipay-method-item"
              :class="{ active: selectedMethod === method.id }"
              @click="selectMethod(method.id)"
            >
              <img style="flex-shrink: 0" :src="method.icon" :alt="method.name" />
              <span>{{ method.name }}</span>
            </div>
          </div>

          <!-- PayPal Button Container -->
          <div v-show="selectedMethod === 'paypal'" id="paypal-button-container"></div>

          <!-- Order Expiration -->
          <div class="order-expiration">
            <el-alert
              :title="$t('payment.orderExpiration')"
              type="warning"
              show-icon
            >
              <div class="countdown">
                {{ $t('payment.timeRemaining') }}: {{ formatCountdown }}
              </div>
            </el-alert>
          </div>
        </div>
      </div>
    </div>
    <foot></foot>
  </div>
</template>

<script>
import {http} from '@/api/api'
import paypalPayment from '@/api/paypalPayment'
import alipayPayment from '@/api/alipayPayment'
import dayjs from 'dayjs'
import { AMSCashierPayment } from '@alipay/ams-checkout'
export default {
  name: 'payment',
  data() {
    return {
      isMobile: false,
      order: {
        ship: {},
        cycle: {},
        userList: []
      },
      selectedMethod: '',
      processing: false,
      countdown: 180,
      timer: null,
      paypalButtonRendered: false,
      paymentMethods: [
        {
          id: 'paypal',
          name: 'PayPal',
          icon: require('@/assets/images/paypal.png')
        },
        {
          id: 'ALIPAY_CN',
          name: '支付宝',
          icon: require('@/assets/images/alipay.png')
        },
        {
          id: 'ALIPAY_HK',
          name: '',
          icon: require('@/assets/images/alipay_hk.png')
        },
        { id: 'RABBIT_LINE_PAY', name: 'RABBIT_LINE_PAY', icon: require('@/assets/images/linepay.png') },
        { id: 'TNG', name: 'TNG', icon: require('@/assets/images/tng.png') }
      ],
      checkoutApp: null
    }
  },
  computed: {
    formatCountdown() {
      const minutes = Math.floor(this.countdown / 60)
      const seconds = this.countdown % 60
      return `${minutes}:${seconds.toString().padStart(2, '0')}`
    }
  },
  watch: {
    selectedMethod(method) {
      if (!method) return
      if (method === 'paypal' && !this.paypalButtonRendered) {
        this.$nextTick(() => {
          this.loadPayPalButton()
        })
      } else {

        /**
         * 确认对话框
         */
        /**
         * -alipay（大陆）
         * -alipayhk（香港）
         * -touch and go ewallet（新加坡马来西亚）
         * -linepay或街口支付（台湾）
         */
        this.confirmPayment().then(async (confirm) => {
          if (!confirm) return;
          let language = navigator.language || navigator.userLanguage;
          language = language.replace("-", "_"); // Replace "-" with "_"
          console.log('language',language)
          this.checkoutApp = new AMSCashierPayment({
            environment: "sandbox",
            locale: language,
            onLog: ({code, message}) => {
              console.log('加载日起至',code, JSON.parse(message))
            },
            onEventCallback: ({code, message, result}) => {
              console.log('时间回调', message, result)
              switch (code) {
                case 'SDK_PAYMENT_SUCCESSFUL':
                  // 支付成功。建议您重定向到支付结果页。
                  console.log('支付成功', result);
                  break;
                case 'SDK_PAYMENT_PROCESSING':
                  console.log('可检查支付结果数据', result);
                  // 支付处理中。建议您通过服务端查询支付状态或等待支付结果通知，同时可询问用户是否完成，如果未完成，可以引导用户重新支付。
                  break;
                case 'SDK_PAYMENT_FAIL':
                  console.log('可检查支付结果数据', result);
                  // 支付失败。建议您查阅文中事件码部分的处理建议，并引导用户重新支付。
                  break;
                case 'SDK_PAYMENT_CANCEL':
                  // 用户在未提交订单状态下退出支付页面。可以用在有效期内的 paymentSessionData 重新调用SDK。如已过期，需要重新请求 paymentSessionData。
                  break;
                case 'SDK_PAYMENT_ERROR':
                  console.log('可检查支付结果数据', result);
                  // 支付状态异常。建议您通过服务端查询支付状态或等待支付结果通知，或引导用户重新支付。
                  break;
                case 'SDK_END_OF_LOADING':
                  // 建议您结束自定义加载动画
                  break;
                case 'SDK_CALL_URL_SUCCESS':
                  console.log('跳转支付方式', result);
                  break
                default:
                  break;
              }
            },
          })
          this.loadAliPay()
        })
      }
    }
  },
  methods: {
    checkDevice() {
      this.isMobile = window.innerWidth <= 750
    },
    selectMethod(method) {
      this.selectedMethod = method;
    },
    /**
     * paypal支付相关
     * @returns {Promise<void>}
     */
    async loadPayPalButton() {
      if (this.paypalButtonRendered) return

      try {
        await this.loadPayPalSDK()

        window.paypal.Buttons({
          style: {
            layout: 'vertical',
            color: 'blue',
            shape: 'rect',
            label: 'paypal'
          },
          createOrder: async () => {
            try {
              const response = await paypalPayment.createPayPalOrder(this.$route.query.orderId)
              if (response.code === 200) {
                return response.data.paypalOrderId
              } else {
                throw new Error(response.message || '创建PayPal订单失败')
              }
            } catch (error) {
              this.$message.error(error.message || '创建PayPal订单失败')
              throw error
            }
          },
          onApprove: async (data) => {
            try {
              const response = await paypalPayment.verifyPayPal({
                orderId: this.$route.query.orderId,
                paypalOrderId: data.orderID
              })

              if (response.code === 200) {
                this.$message.success(this.$t('payment.paymentSuccess'))
                this.$router.push({
                  path: '/payment/success',
                  query: { orderId: this.$route.query.orderId }
                })
              } else {
                throw new Error(response.message || '支付验证失败')
              }
            } catch (error) {
              this.$message.error(error.message || this.$t('payment.paymentFailed'))
            }
          },
          onError: (err) => {
            console.error('PayPal Error:', err)
            this.$message.error(this.$t('payment.paymentError'))
          }
        }).render('#paypal-button-container')

        this.paypalButtonRendered = true
      } catch (error) {
        console.error('PayPal initialization error:', error)
        this.$message.error(this.$t('payment.paypalInitializationError'))
      }
    },
    loadPayPalSDK() {
      return new Promise((resolve, reject) => {
        if (window.paypal) {
          resolve()
          return
        }

        const script = document.createElement('script')
        script.src = `https://sandbox.paypal.com/sdk/js?client-id=AZeTyR3oqVmNGVs9yBdi6IZ58Os-WUDnu6w601SkqLES8WU7z9v7HmWFlU7tE1c7VXg538dmKrhWcFlj&currency=AUD`
        script.async = true

        script.onload = () => resolve()
        script.onerror = () => reject(new Error('Failed to load PayPal SDK'))

        document.body.appendChild(script)
      })
    },
    /**
     * 阿里支付
     */
    async loadAliPay() {
      // 步骤二：服务端调用支付会话创建接口，获取paymentSessionData
      let paymentSessionData = ''
      const response = await alipayPayment.createAlipayOrder({
        orderId: this.$route.query.orderId,
        paymentMethodType: this.selectedMethod
      })
      console.log('response',response)
      // 获取响应中的paymentSessionData参数值
      paymentSessionData = response.data.paymentSessionData;
      // 步骤三：创建渲染卡组件
      // 最佳实践
      await this.checkoutApp.createComponent({
        paymentSessionData: paymentSessionData,
        appearance:{
          showLoading: true, // 默认为true，表示展示初始化加载动画
        },
      });
    },
    /**
     * 订单相关
     * @returns {Promise<void>}
     */
    async loadOrder() {
      try {
        const response = await http.order.read(this.$route.query.orderId)
        if (response.code === 200) {
          if (response.data.status_value !== 'wait_pay') {
            this.$message.error(this.$t('payment.orderExpired'))
            this.$router.push('/')
            return
          }
          this.order = {
            ...response.data,
          }
          // Calculate remaining time
          const createdTime = dayjs(response.data.create_time)
          const now = dayjs()
          const diffSeconds = 180 - now.diff(createdTime, 'second')
          this.countdown = Math.max(0, diffSeconds)

          if (this.countdown === 0) {
            this.$message.error(this.$t('payment.orderExpired'))
            // this.$router.push('/products')
            return
          }

          this.startCountdown()
        }
      } catch (error) {
        this.$message.error(this.$t('payment.orderExpired'))
        // this.$router.push('/products')
      }
    },
    startCountdown() {
      this.timer = setInterval(() => {
        if (this.countdown > 0) {
          this.countdown--
        } else {
          clearInterval(this.timer)
          this.$message.error(this.$t('payment.orderExpired'))
          this.$router.push('/products')
        }
      }, 1000)
    },
    confirmPayment() {
      return this.$confirm(this.$t('pay.tips', { n: this.selectedMethod}), this.$t('pay.confirmPay'), {
        confirmButtonText: this.$t('pay.sure'),
        cancelButtonText: this.$t('pay.cancel'),
        type: 'warning'
      }).catch(() => {
        this.selectedMethod = ''
      });
    }
  },
  created() {
    this.loadOrder()
  },
  mounted() {
    this.checkDevice()
    window.addEventListener('resize', this.checkDevice)
  },
  beforeDestroy() {
    this.checkoutApp && this.checkoutApp.unmount();
    window.removeEventListener('resize', this.checkDevice)
    if (this.timer) {
      clearInterval(this.timer)
    }
  }
}
</script>

<style lang="less" scoped>
.payment-container {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;

  h2 {
    font-size: 20px;
    margin-bottom: 20px;
    color: #333;
  }
}

.order-summary {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .summary-content {
    .summary-item {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 12px 0;

      &:last-child {
        border-bottom: none;
      }

      &.total {
        margin-top: 10px;
        padding-top: 20px;
        border-top: 1px solid #e8e8e8;
        font-size: 18px;
        font-weight: bold;
        color: #0F7CD0;
      }

      .label {
        color: #666;
      }

      .value {
        color: #333;
      }
    }
  }
}

.payment-section {
  background: #fff;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);

  .payment-methods {
    display: flex;
    gap: 20px;
    margin-bottom: 20px;
    margin-top: 20px;

    .payment-method {
      display: flex;
      align-items: center;
      gap: 10px;
      padding: 15px;
      border: 1px solid #dcdfe6;
      border-radius: 4px;
      cursor: pointer;
      transition: all 0.3s;

      &:hover {
        border-color: #409eff;
      }

      &.active {
        border-color: #409eff;
        background-color: #ecf5ff;
      }

      img {
        height: 40px;
        object-fit: contain;
      }

      span {
        font-size: 14px;
      }
    }
  }

  .alipay-methods {
    margin-top: 20px;
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 15px;

    .alipay-method-item {
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 10px;
      border: 1px solid #e8e8e8;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;

      &:hover {
        border-color: #40a9ff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.09);
      }

      &.active {
        border-color: #1890ff;
        background-color: #e6f7ff;
      }

      img {
        height: 32px;
        margin-right: 10px;
      }

      span {
        font-size: 14px;
        color: #333;
      }
    }
  }

  #paypal-button-container {
    margin: 20px 0;
    min-height: 150px;
  }

  .pay-btn {
    width: 100%;
    height: 44px;
    margin: 20px 0;
    background-color: #0F7CD0;
    border-color: #0F7CD0;

    &:hover {
      background-color: darken(#0F7CD0, 5%);
      border-color: darken(#0F7CD0, 5%);
    }
  }
}

.order-expiration {
  margin-top: 20px;

  .countdown {
    margin-top: 5px;
    color: #e6a23c;
    font-size: 14px;
  }
}

.is-mobile {
  .payment-container {
    padding: 15px;
  }

  .payment-methods {
    flex-direction: column;

    .payment-method {
      width: 100%;
      justify-content: center;
    }
  }
}
</style>
